package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.*;
import csu.web.mypetstore.persistence.AccountDao;
import csu.web.mypetstore.persistence.impl.AccountDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class OrderJsServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session = req.getSession();//先前一直用session，取不到值why？？
        String address=req.getParameter("address");

        Cart cart = (Cart) session.getAttribute("cart");
        if(cart==null){
            cart = new Cart();
        }
        Iterator<CartItem> cartItemss= cart.getAllCartItems();
        List<CartItem> cartItems = cart.getCartItemList();

        while (cartItemss.hasNext()) {
            CartItem cartItem = (CartItem) cartItemss.next();
            String itemId = cartItem.getItem().getItemId();
            try {
                String quantityString = req.getParameter(itemId);
                int quantity =Integer.parseInt(quantityString);

                cart.setQuantityByItemId(itemId, quantity);
                if (quantity < 1) {
                    cartItemss.remove();
                }
            } catch (Exception e) {
                //ignore parse exceptions on purpose
            }
        }
        AccountDao accountDao = new AccountDaoImpl();
        Account loginAccount = (Account) session.getAttribute("loginAccount");

        if (loginAccount != null) { //更新订单
            //accountDao.deleteShoppingcartByUsername(loginAccount);
            //待解决,如何更新数量为0的数据

            while(cartItems.size()>0){
                CartItem cartItem = cartItems.get(0);
                cart.setQuantityByItemId(cartItem.getItem().getItemId(),0);
                cart.removeItemById(cartItem.getItem().getItemId());
                accountDao.updateShoppingcartByAddress(loginAccount,cartItem,address);
                accountDao.updateShoppingcartTimesByUsernameAndItemid(loginAccount,cartItem);
            }
        }

        session.setAttribute("cart", cart);
    }
}
